<template>
	<view class="menu-btn-area" :style="{height: `${navHeight}px`, paddingTop: `${navTop}px`}">
		<uni-data-picker ref="datePickerRef" v-model="classifyId" :localdata="baseQuestionStore.cascadeList"
			popup-title="题目类型" :clear-icon="false" placeholder="请选择题目类型" @change="onSelectClassify"
			@popupopened="onPopupSelect" @popupclosed="onPopupClose">
		</uni-data-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance
	} from "vue";
	import {
		onHide
	} from '@dcloudio/uni-app'
	import {
		useBaseQuestionStore
	} from '@/store';
	import useMenuButton from '@/hook/use-menu-button';

	// 获取胶囊信息
	const [navHeight, navTop] = useMenuButton()

	// 获取仓库数据
	const baseQuestionStore = useBaseQuestionStore()

	// 级联选择器选中的value值
	const classifyId = ref('')
	// 级联选择器的级数
	const type = ref(1)
	// 级联选择器的实例
	const datePickerRef = ref()

	// 页面挂载时的钩子
	onMounted(() => {
		baseQuestionStore.openCascadeSelectAction(openCascadeSelect)
	})

	// 页面隐藏的钩子
	onHide(() => {
		// 关闭级联选择器的框
		datePickerRef.value.hide()
	})

	// 选择题目类型触发的回调
	const onSelectClassify = ({
		detail
	}) => {
		const len = detail.value?.length
		// 保存选中的级数
		type.value = len - 1
		// 发送请求获取题目对应的统计信息
		baseQuestionStore.getClassifyRecordAction(classifyId.value, type.value)
		// 保存当前题库的 类型id和级别数type
		baseQuestionStore.saveQuestionParamsAction(classifyId.value, type.value).then(() => {
			// 判断是否是选择了类型还要跳转答题页面的情况
			// 因为会执行onPopupClose函数关闭窗口再执行这里面的代码，所以无论如何都会关闭一次窗口，这里是通过窗口关闭的次数来决定
			// 需不需要跳转到答题页面；如果关闭的次数大于1证明是左上角的选择，左上角选择是不需要跳转到答题页面的
			if (baseQuestionStore.isNeedSelect && baseQuestionStore.closeTimes === 1) {
				baseQuestionStore.afterSelect()
			}
		})
	}

	// 点击选择框的时候
	const onPopupSelect = () => {
		// 获取分类数据
		baseQuestionStore.getClassifyCascadeDataAction()
	}

	// 关闭选择框的时候
	const onPopupClose = () => {
		baseQuestionStore.closeTimes++
	}

	// 封装一个打开选择框的方法
	const openCascadeSelect = () => {
		datePickerRef.value.show()
	}
</script>

<style lang="scss">
	.menu-btn-area {
		display: flex;
		align-items: center;
		border-bottom: 2rpx solid #d0ccd1;

		position: fixed;
		padding: 0 0 10rpx 0;
		left: 30rpx;
		right: 30rpx;
		top: 0;
		z-index: 99;
	}
</style>